const fs = require('fs');
// const vueCompiler=require('vue-template-compiler');
import * as vueCompiler from 'vue-template-compiler'
// const {compileTemplate}=require('@vue/component-compiler-utils');
import { compileTemplate } from '@vue/component-compiler-utils';
import { getWorkPath } from '../../env'
import { toVueTemplate } from './toVueTemplate'
import { writeFile } from './writeFile'

export function compileWxml(moduleDeps) {
    let list = [];
    console.log("moduleDeps:", moduleDeps)

    for (const path in moduleDeps) {
        const code = compile(path, moduleDeps[path].moduleId);
        list.push({ code, path });
    }
    writeFile(list);
}

//编译wxml文件
function compile(path, moduleId) {
    //获取工作目录
    const workPath = getWorkPath();
    //获取wxml文件路径
    const wxmlFullPath = `${workPath}/${path}.wxml`;
    //读取wxml文件内容
    const wxmlContent = fs.readFileSync(wxmlFullPath, { encoding: 'utf-8' });
    //将wxml文件内容转换为vue组件模板
    const vueTemplate = toVueTemplate(wxmlContent.trim());
    // console.log(vueTemplate);
    const compileResult = compileTemplate({
        source: vueTemplate,
        compiler: vueCompiler,
        // filename:`${path}.wxml`,
    })
    // console.log(compileResult);
    const code = `
        modDefine('${path}',function(){

            ${compileResult.code}

            Page({
                path:'${path}',
                render:render,
                usingComponents:{},
                scopeId:'data-v-${moduleId}',
            })
        })
    `;
    return code;
}

